import { fileURLToPath } from "url";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import postCssPxToRem from "postcss-pxtorem";
import postcss100vhFix from "postcss-100vh-fix";
import postcssPresetEnv from "postcss-preset-env";
import postcssNested from "postcss-nested";
import postcssAssets from "postcss-assets";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";

// https://vitejs.dev/config/
const config = {
  plugins: [
    vue({ reactivityTransform: true }),
    Components({
      resolvers: [VantResolver()],
    }),
  ],
  base: "./",
  server: {
    host: "0.0.0.0",
    port: 1999,
    proxy: {
      "/api": {
        target: "https://api.fancy-metal.com/api",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  build: {
    outDir: "fancymetal-admin",
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      "@views": fileURLToPath(new URL("./src/views", import.meta.url)),
      "@utils": fileURLToPath(new URL("./src/utils", import.meta.url)),
      "@img": fileURLToPath(new URL("./src/assets", import.meta.url)),
      "@com": fileURLToPath(new URL("./src/components", import.meta.url)),
      "@req": fileURLToPath(new URL("./src/utils/request", import.meta.url)),
    },
  },
  css: {
    postcss: {
      plugins: [
        postcssNested(), // 可以嵌套书写css
        postcssPresetEnv({}), // 兼容低版本浏览器语法和自动添加前缀，读取根目录下的 .browserslistrc文件
        // postCssPxToRem({
        //   // 自适应，px>rem转换
        //   rootValue: 100, // 75表示750设计稿，37.5表示375设计稿
        //   propList: ["*"], // 需要转换的属性，这里选择全部都进行转换
        //   unitPrecision: 5, //最多小数位数;
        //   replace: true,
        //   mediaQuery: false, //允许在媒体查询中转换px
        //   minPixelValue: 2, //设置要替换的最小像素值
        //   // selectorBlackList: [""], // 过滤掉norem-开头的class，不进行rem转换
        // }),
        postcss100vhFix(), // safari浏览器下100vh单位的兼容
        postcssAssets({
          loadPaths: ["src/assets/images"], // 资源引入路径,
        }), // 更强大的资源引入
      ],
    },
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/assets/styles/_mixins.scss";`,
      },
    },
  },
};

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  // console.log("env.VITE_BASE", env.VITE_BASE);
  if (env.VITE_BASE) {
    config.base = env.VITE_BASE;
  }
  return config;
});
